//
//  CommentViewController.m
//  jipin
//
//  Created by lcb on 5/21/15.
//  Copyright (c) 2015 liuchengbin. All rights reserved.
//

#import "CommentViewController.h"
#import "CellConfig.h"
#import "HcCustomKeyboard.h"
#import "ZToastManager.h"
#import "BaseModel.h"
@interface CommentViewController ()<UITableViewDataSource,UITableViewDelegate,HcCustomKeyboardDelegate>
@property(nonatomic,strong)UITableView *tbView;
@property(nonatomic,strong)NSMutableArray *dataArray;
@property(nonatomic,assign)BOOL isLoadFinished;
@property(nonatomic,assign)BOOL isRequesting;
@property(nonatomic,assign)int currentPage;
@property(nonatomic,strong) HcCustomKeyboard *keyBordView;
@end

@implementation CommentViewController
@synthesize dictionary=_dictionary;
@synthesize fromType =_fromType;
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor =[UIColor whiteColor];
    self.isComment = YES;
    self.navTitle =@"点评";
    self.isLoadFinished =NO;
    self.isRequesting =NO;
    self.currentPage=0;
    if (!_dataArray) {
        _dataArray =[NSMutableArray array];
    }
    [self initUI];
}
-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    self.navigationController.enableBackGesture=YES;
    
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
      DLog(@"%s", __PRETTY_FUNCTION__);
}
-(void)dealloc
{
    self.tbView.dataSource=nil;
    self.tbView.delegate=nil;
    self.tbView=nil;
    [self.dataArray removeAllObjects];
    self.dataArray=nil;
    [HcCustomKeyboard customKeyboard].mDelegate=nil;
    [[HcCustomKeyboard customKeyboard].mTextView removeFromSuperview];
    [HcCustomKeyboard customKeyboard].mTextView=nil;
    [[HcCustomKeyboard customKeyboard].mTextView resignFirstResponder];
    self.keyBordView=nil;
    DLog(@"%s", __PRETTY_FUNCTION__);
}
-(void)initUI
{
    _tbView = [[UITableView alloc] initWithFrame:CGRectMake(0, self.navHeight, self.view.frame.size.width, self.view.frame.size.height-self.navHeight-40) style:UITableViewStylePlain];
    _tbView.delegate = self;
    _tbView.dataSource = self;
    _tbView.backgroundColor = [UIColor whiteColor];
    _tbView.showsVerticalScrollIndicator = NO;
    _tbView.separatorStyle= UITableViewCellSeparatorStyleNone;
    [self.view addSubview:_tbView];
    __weak typeof (self) wSelf = self;
    [_tbView addInfiniteScrollingWithActionHandler:^{
        if (wSelf.isLoadFinished) {
            //停止菊花
         //   [wSelf.tbView.infiniteScrollingView stopAnimating];
            return;
        }
        [wSelf.tbView.infiniteScrollingView startAnimating];
        if ([wSelf.dataArray count]>0) {
            wSelf.currentPage =(int)[wSelf.dataArray count];
        }
        [wSelf getCommentListData];
        [wSelf.tbView.infiniteScrollingView stopAnimating];
    }];
    //
//    [ZShare showAnimationView:self.view center:CGPointZero];
    [self getCommentListData];
//
    [[HcCustomKeyboard customKeyboard] textViewShowView:self customKeyboardDelegate:self];
    if ([self.fromType isEqualToString:@"1"]||[self.fromType isEqualToString:@"3"]) {
         [[HcCustomKeyboard customKeyboard].mTextView  becomeFirstResponder];
    }else if([self.fromType isEqualToString:@"2"])//回复
    {
        NSString *name =[NSString stringWithFormat:@"@%@ ", [self.dictionary objectForKey:@"nick_name"]];
        [[HcCustomKeyboard customKeyboard].mTextView  becomeFirstResponder];
        [HcCustomKeyboard customKeyboard].mTextView.text =name;
    }
    
}
#pragma mark---
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [_dataArray count];
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.row>_dataArray.count) {
        return 0;
    }
    NSDictionary *data =[_dataArray objectAtIndex:indexPath.row];
    if ([self.fromType intValue]==3) {
        return [UserCommentCell returnCellHeight:data];
    }
    return [CommentCell returnCellHeight:data];
}
-(UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    if ([self.fromType intValue]==3) {
        UserCommentCell *cell = (UserCommentCell*)[tableView  dequeueReusableCellWithIdentifier:@"UserCommentCell"];
        if(cell == nil)
        {
            cell = [[UserCommentCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@""];
            _tbView.separatorStyle = UITableViewCellSeparatorStyleNone;
            cell.backgroundColor =[UIColor whiteColor];
            __weak typeof (self) wSelf = self;
            [cell setCallBack:^(BEventType t, UIView *v,id obj,id key,NSIndexPath *indexPath) {
                [wSelf cellAction:t views:v obj:obj key:key indexPath:indexPath];
            }];
        }
        if (indexPath.row>self.dataArray.count) {
            return cell;
        }
        NSDictionary *dict =[self.dataArray objectAtIndex:indexPath.row];
        [cell showInfo:dict key:@"comment" indexPath:indexPath];
        return cell;
    }else{
        CommentCell *cell = (CommentCell*)[tableView  dequeueReusableCellWithIdentifier:@"CommentCell"];
        if(cell == nil)
        {
            cell = [[CommentCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@""];
            cell.backgroundColor=[UIColor whiteColor];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            __weak typeof (self) wSelf = self;
            [cell setCallBack:^(BEventType t, UIView *v,id obj,id key,NSIndexPath *indexPath) {
                [wSelf cellAction:t views:v obj:obj key:key indexPath:indexPath];
            }];
        }
        if (indexPath.row>=[_dataArray count]) {
            return cell;
        }
        NSDictionary *data =[_dataArray objectAtIndex:indexPath.row];
        [cell showInfo:data key:@"CommentCell" indexPath:indexPath];
        return cell;
    }
  //  return cell;
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.row>=[_dataArray count]) {
        return;
    }
    NSDictionary *data =[_dataArray objectAtIndex:indexPath.row];
    NSString *name =[NSString stringWithFormat:@"@%@ ", [data objectForKey:@"nick_name"]];
    [[HcCustomKeyboard customKeyboard].mTextView  becomeFirstResponder];
    [HcCustomKeyboard customKeyboard].mTextView.text =name;
}
-(void)getCommentListData
{
    NSMutableDictionary *dict =[NSMutableDictionary dictionary];
    [dict setValue:[NSString stringWithFormat:@"%d",self.currentPage] forKey:@"from"];
    [dict setValue:self.photo_id forKey:@"photo_id"];
    self.isRequesting =YES;
    __weak typeof (self) wSelf = self;
    wSelf.isRequesting = YES;
    [BaseModel commentList:dict success:^(AFHTTPRequestOperation *operation, NSObject *result) {
        [wSelf parserResultObject:result];
        wSelf.isRequesting = NO;
        [_tbView.infiniteScrollingView stopAnimating];
         [[ZToastManager ShardInstance] hideprogress];
   //     [ZShare hiddenAnimationView:wSelf.view];
    } failure:^(NSError *error) {
        [_tbView.infiniteScrollingView stopAnimating];
         [[ZToastManager ShardInstance] hideprogress];
        wSelf.isRequesting = NO;
   //     [ZShare hiddenAnimationView:wSelf.view text:@""];
    }];

}
-(void)parserResultObject:(id)resultObject
{
    if (resultObject==nil) {
        return;
    }
    if (resultObject && [resultObject isKindOfClass:[NSDictionary class]]) {
        
        id dataarray =[resultObject objectForKey:@"data"];
        if (dataarray && [dataarray isKindOfClass:[NSArray class]]) {
            if (self.currentPage == 0 && [dataarray count]>0) {
                [_dataArray removeAllObjects];
            }
            for (id di in dataarray) {
                if (di && [di isKindOfClass:[NSDictionary class]])
                {
                    [_dataArray addObject:di];
                }
            }
        }
        
        self.isLoadFinished =  [[resultObject objectForKey:@"end"] boolValue];
        if (self.isLoadFinished)
        {
            
            NSString *end_msg =[resultObject objectForKey:@"end_msg"];
            self.tbView.tableFooterView =[ZShare footerView:end_msg];
            
            [self.tbView.infiniteScrollingView stopAnimating];
            [self.tbView setShowsInfiniteScrolling:NO];
        }
    }
    
    [self.tbView reloadData];
    self.isRequesting = NO;
   
}
//
-(void)talkBtnClick:(UITextView *)textViewGet
{
    if(textViewGet.text.length==0)
    {
        [[ZToastManager ShardInstance] showtoast:@"请输入内容"];
        return;
    }
    if ([self isLogin]) {
      [self postComment:textViewGet.text];
    }
}
//
-(void)backBtnClick
{
    self.tbView.dataSource=nil;
    self.tbView.delegate=nil;
    self.tbView=nil;
    [self.dataArray removeAllObjects];
    self.dataArray=nil;
    [[HcCustomKeyboard customKeyboard] textViewShowView:nil customKeyboardDelegate:nil];
    [HcCustomKeyboard customKeyboard].mDelegate=nil;
     [[HcCustomKeyboard customKeyboard].mTextView resignFirstResponder];
    [[HcCustomKeyboard customKeyboard].mTextView removeFromSuperview];
    [HcCustomKeyboard customKeyboard].mTextView=nil;
    self.keyBordView=nil;
    [self.navigationController popViewControllerAnimated:YES];
}
-(void)postComment:(NSString*)txt
{
    NSMutableDictionary *dict =[NSMutableDictionary dictionary];
    [dict setValue:@"comment" forKey:@"action"];
    [dict setValue:@"" forKey:@"comment_id"];
    if ([self.fromType intValue]==3) {
        NSString *good_id =[[NSString stringWithFormat:@"%@",[self.dictionary objectForKey:@"photo_id"]] replaceNullString];
        [dict setValue:self.photo_id forKey:@"good_id"];
        [dict setValue:good_id forKey:@"photo_id"];
    }else{
        [dict setValue:self.photo_id forKey:@"photo_id"];
         [dict setValue:@"" forKey:@"good_id"];
    }
   
    [dict setValue:txt forKey:@"text"];
    
    self.isRequesting =YES;
    __weak typeof (self) wSelf = self;
    wSelf.isRequesting = YES;
    [BaseModel comment:dict success:^(AFHTTPRequestOperation *operation, NSObject *result) {
        [wSelf commentResultObject:result];
    } failure:^(NSError *error) {
        [[ZToastManager ShardInstance] showtoast:@"点评失败"];
   //     [ZShare hiddenAnimationView:wSelf.view text:@""];
    }];
 
}

-(void)commentResultObject:(id)resultObject
{
    if (resultObject==nil) {
        return;
    }
    if (resultObject && [resultObject isKindOfClass:[NSDictionary class]]) {
        {
            [[ZToastManager ShardInstance] showtoast:[resultObject objectForKey:@"msg"]];
            id comments =[resultObject objectForKey:@"comments"];
            if (comments && [comments isKindOfClass:[NSArray class]]) {
                for (id cmt in comments) {
                    if (cmt && [cmt isKindOfClass:[NSDictionary class]]) {
                        [_dataArray insertObject:cmt atIndex:_dataArray.count];
                    }
                }
            }
           
            id  comment_js =[resultObject objectForKey:@"comment_js"];
            if (comment_js && [comment_js isKindOfClass:[NSString class]])
            {
                [[NSNotificationCenter defaultCenter] postNotificationName:@"updatejs" object:comment_js];
            }
           
            id score =[resultObject objectForKey:@"score"];
            if (score && [score isKindOfClass:[NSDictionary class]]) {
                NSString *scoreMsg =[score objectForKey:@"score_msg"];
                [WTStatusBar setStatusText:scoreMsg timeout:3 animated:YES];
            }
        }
        [[NSNotificationCenter defaultCenter] postNotificationName:@"updateCommentList" object:nil];
    }
    
    [_tbView reloadData];
}
-(void)cellAction:(BEventType)type views:(UIView *)v obj:(id)obj key:(id)key indexPath:(NSIndexPath *)indexPath
{
    switch (type) {
        case BEventType_ding:
        {
            NSString *cmid =[NSString stringWithFormat:@"%@",[obj objectForKey:@"comment_id"]];
            int had_top=[[obj objectForKey:@"had_top"] intValue];
            if(had_top)
            {
                [[ZToastManager ShardInstance] showtoast:@"已顶"];
                return;
            }
            if ([self isLogin]) {
                [self postTop:cmid type:1];
            }
            
        }
            break;
        case BEventType_cai:
        {
             NSString *cmid =[NSString stringWithFormat:@"%@",[obj objectForKey:@"comment_id"]];
             int had_bottom=[[obj objectForKey:@"had_bottom"] intValue];
            if(had_bottom)
            {
                [[ZToastManager ShardInstance] showtoast:@"已踩"];
                return;
            }
            if ([self isLogin]) {
              [self postTop:cmid type:2];
            }
        }
            break;
        default:
            break;
    }
}
//顶踩
-(void)postTop:(NSString*)comment_id type:(int)type
{
    NSMutableDictionary *dict =[NSMutableDictionary dictionary];
    if (type==1) {
          [dict setValue:@"push_top" forKey:@"action"];
    }else{
         [dict setValue:@"push_bottom" forKey:@"action"];
    }
    [dict setValue:comment_id forKey:@"comment_id"];
    [dict setValue:@"" forKey:@"photo_id"];
    [dict setValue:@"" forKey:@"text"];
    
    __weak typeof (self) wSelf = self;
    [BaseModel comment:dict success:^(AFHTTPRequestOperation *operation, id result) {
        [[ZToastManager ShardInstance] showtoast:[result objectForKey:@"msg"]];
        if ([result isKindOfClass:[NSDictionary class]]) {
            NSDictionary *resultt = (NSDictionary*)result;
            [[ZToastManager ShardInstance] showtoast:@"评论成功！"];
          
            id  comment_js =[resultt objectForKey:@"comment_js"];
            if (comment_js && [comment_js isKindOfClass:[NSString class]])
            {
                  [[NSNotificationCenter defaultCenter] postNotificationName:@"updatejs" object:comment_js];
            }
        }
     
        
        [wSelf getCommentListData];
        [_tbView reloadData];
        
    } failure:^(NSError *error) {
        [[ZToastManager ShardInstance] showtoast:@"顶踩失败"];
    //    [ZShare hiddenAnimationView:wSelf.view text:@""];
    }];
    
}
@end
